package com.lingxu.base.system.manage.util;

import com.lingxu.base.system.orgManage.entity.MenuTree;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Title: MenuTreeUtil
 * @Package: com.lingxu.base.system.manage.util
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2023/7/31 14:43
 * @Description:
 * @Version: 1.0.0
 */
public class MenuTreeUtil {

    private List<MenuTree> menuList = new ArrayList<>();
    // 带参构造器，将数据库中的菜单数据记录，装载在我们承载菜单的列表中

    public MenuTreeUtil(List<MenuTree> menuList){
        this.menuList = menuList;
    }

    // 获取根节点
    public List<MenuTree> getRootNode(){
        List<MenuTree> rootNode = new ArrayList<>();
        for (MenuTree menu : menuList) {
            if (StringUtils.isEmpty(menu.getPid())){
                rootNode.add(menu);
            }
        }
        return rootNode;
    }

    // 构建子树
    public MenuTree buildChildren(MenuTree rootNode){
        List<MenuTree> childrenTree = new ArrayList<>();
        for (MenuTree menu : menuList) {
            if (rootNode.getId().equals(menu.getPid())){
                childrenTree.add(buildChildren(menu));
            }
        }
        rootNode.setMenuChildTree(childrenTree);
        return rootNode;
    }

    // 构建树
    public List<MenuTree> buildTree(){
        List<MenuTree> menus = getRootNode();
        for (MenuTree menu : menus) {
            buildChildren(menu);
        }
        return menus;
    }

}
